<template>
  <a-card title="编辑房户信息" style="width: 600px; pointer-events: all">
    <template #extra>
      <a-select
        ref="select"
        v-model:value="selectBuild"
        style="width: 120px"
        :options="buildsOption"
        @change="handleChange"
      ></a-select>
    </template>
    <a-table
      size="small"
      bordered
      :data-source="houseList"
      :loading="loading"
      :columns="buildingColumns"
      :pagination="pagination"
      @change="handlePaginationChange"
    >
      <template #bodyCell="{ column, text, record }">
        <template
          v-if="
            ['doorNumText', 'floorNumText', 'numberText'].includes(
              column.dataIndex
            )
          "
        >
          <a-tag
            :color="column.dataIndex === 'doorNumText' ? 'red' : 'green'"
            >{{ text }}</a-tag
          >
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a @click="edit(record)">编辑信息</a>
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'positionFix'">
          <div @click="focusOnArea(record)">
            <img
              style="cursor: pointer"
              width="20"
              height="20"
              src="/src/assets/position.png"
              alt=""
            />
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <FormInfo :formData="formData" :formOpen="formOpen" @onClose="onClose" />
</template>

<script setup>
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
import { getBuild, getHouse, getOneHouseInfo } from '@/api/api'
import { ref, onMounted, reactive, onBeforeUnmount } from 'vue'
import FormInfo from './FormInfo.vue'
import { useMapData } from '@/store'
import Label from 'cesium/Source/Scene/Label'

const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const selectBuild = ref('')
// 楼栋列表
const buildsOption = ref([])
// 提交的表单信息
const formData = ref({})
// 外部组件控制表单显隐
const formOpen = ref(false)
const loading = ref(false)
// 选中的楼栋

const pagination = reactive({
  total: 0,
  current: 0,
  pageSize: 0,
})
const buildingColumns = ref([
  {
    title: '门牌号',
    dataIndex: 'doorNumText',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '单元号',
    dataIndex: 'numberText',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '楼层',
    dataIndex: 'floorNumText',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '定位',
    dataIndex: 'positionFix',
    align: 'center',
    width: '10%',
  },
])

// 楼栋信息
const houseList = ref([])
// 当前渲染的图元
let primitiveHouse
let currentBuildEnt
let currentBuild

onMounted(async () => {
  const info = await getBuild()
  if (info.code === 200) {
    const { data } = info
    console.log(info)
    buildsOption.value = data.map((item) => {
      return {
        value: item.id,
        label: item.name,
        polygon: item.polygon,
      }
    })
  }
})

const getHouseInfo = async (queryParam) => {
  loading.value = true
  const info = await getHouse(queryParam)
  if (info.code === 200) {
    const {
      data: { list, total },
    } = info
    const tableData = []
    list.forEach((item) => {
      // 门牌号=floorNum+number
      const { floorNum, number } = item
      const doorNumText = `${floorNum}-0${number}`
      const numberText = `0${number}`
      const floorNumText = `${floorNum}楼`

      // 构造表格数据
      tableData.push({
        ...item,
        doorNumText,
        numberText,
        floorNumText,
      })
    })
    houseList.value = tableData
    // 填充分页的数据
    pagination.total = total
    pagination.pageSize = houseList.value.length
    pagination.current = queryParam.pageIndex
  }
  loading.value = false
}

const handleChange = async (e) => {
  currentBuild = buildsOption.value.find((item) => item.value === e)
  if (currentBuild) {
    const { polygon, label } = currentBuild
    // 将三维的coordinates数据变为一维的经纬度数组，然后转笛卡尔数组，再转PolygonHierarchy
    const { coordinates } = polygon

    const center = turf.center(polygon)
    const {
      geometry: { coordinates: centerLng },
    } = center
    viewer.camera.flyTo({
      destination: new Cesium.Cartesian3.fromDegrees(
        centerLng[0],
        centerLng[1],
        500
      ),
    })

    const positions = coordinates[0].reduce((a, b) => a.concat(b), [])
    const cartesian = new Cesium.Cartesian3.fromDegreesArray(positions)
    const ent = new Cesium.Entity({
      name: label,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(cartesian),
        material: Cesium.Color.RED.withAlpha(0.6),
        classificationType: Cesium.ClassificationType.BOTH,
      },
    })
    viewer.entities.add(ent)

    // 3.请求接口，渲染表格
    const queryParam = {
      id: e,
      pageIndex: 1,
    }

    getHouseInfo(queryParam)
  }
}
// 切换分页
const handlePaginationChange = (pagination) => {
  const { current } = pagination
  const queryParam = {
    id: currentBuild.value,
    pageIndex: current,
  }
  getHouseInfo(queryParam)
}

const focusOnArea = (record) => {
  if (primitiveHouse) {
    viewer.scene.primitives.remove(primitiveHouse)
  }

  if (currentBuild) {
    const { maxHeight, minHeight } = record
    const { polygon } = currentBuild

    const { coordinates } = polygon
    const positions = coordinates[0].reduce((a, b) => a.concat(b), [])
    const cartesian = new Cesium.Cartesian3.fromDegreesArray(positions)
    const hierachy = new Cesium.PolygonHierarchy(cartesian)
    const geometryInstance = new Cesium.GeometryInstance({
      geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: hierachy,
        height: minHeight,
        extrudedHeight: maxHeight,
      }),
      // 这里务必把颜色写在instance中，因为每一户的颜色都不一样，所以不能用appearance来指定颜色
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.YELLOW.withAlpha(0.6)
        ),
      },
    })

    const p = new Cesium.ClassificationPrimitive({
      geometryInstances: geometryInstance,
      classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
    })
    primitiveHouse = viewer.scene.primitives.add(p)
  }
}

const edit = async (record) => {
  const { id, floorNum, number } = record
  const res = await getOneHouseInfo({ id })
  if (res.code === 200) {
    // 打开表单
    formOpen.value = true
    let houseNum = number > 9 ? number : '0' + number
    const houseAddress = number + '单元' + floorNum + houseNum
    res.data.houseAddress = houseAddress
    res.data.id = id
    formData.value = res.data
  }
}

const onClose = () => {
  formOpen.value = false
}
</script>
